<template>
  <div>
    <!-- 导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>采购管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 商品列表主体 -->
    <el-card>
      <!-- 搜索区域 -->
      <el-row :gutter="25">
        <el-col :span="10">
          <!-- 搜索框 -->
          <el-input 
            placeholder="请输入搜索内容" 
            v-model="queryInfo.query" 
            clearable
            @clear="getProductList"
          >
            <template #append>
              <el-button 
                icon="el-icon-search" 
                @click="getProductList"
              ></el-button>
            </template>
          </el-input>
        </el-col>
        <el-col :span="4">
        <el-select v-model="selectedVarietyType" placeholder="请选择种类" @change="getProductList">
          <el-option label="无" value=""></el-option>
          <el-option
            v-for="type in varietyTypes"
            :key="type"
            :label="type"
            :value="type">
          </el-option>
        </el-select>
        </el-col>
        <!-- 修改后的按钮 -->
        <el-col :span="4">
          <el-button type="primary" icon="el-icon-refresh" @click="refreshData">
            刷新
          </el-button>
        </el-col>
      </el-row>

      <!-- 商品列表部分 -->
  <el-table :data="productList" border stripe @sort-change="handleSortChange">
    <el-table-column type="index"></el-table-column>
    <el-table-column label="市场" prop="market" sortable="custom"></el-table-column>
    <el-table-column label="商品名称" prop="product" sortable="custom"></el-table-column>
    <el-table-column label="最高价" prop="highestPrice" sortable="custom"></el-table-column>
    <el-table-column label="最低价" prop="lowestPrice" sortable="custom"></el-table-column>
    <el-table-column label="批发价" prop="bulkPrice" sortable="custom"></el-table-column>
    <el-table-column label="货量（吨）" prop="quantity"sortable="custom" ></el-table-column>
    <el-table-column label="产地" prop="origin"></el-table-column>
    <!-- 操作列保持不变 -->
    <el-table-column label="操作">
      <template v-slot:default="scope">
        <el-button type="primary" icon="el-icon-shopping-cart-2" size="mini" @click="handlePurchase(scope.row)">采购</el-button>
      </template>
    </el-table-column>
  </el-table>

      <!-- 分页组件 -->
      <div>
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="queryInfo.pageNum"
          :page-sizes="[5, 10, 20, 50]"
          :page-size="queryInfo.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
        </el-pagination>
      </div>
    </el-card>
  </div>
</template>

<script>
import axios from 'axios';
export default {
  created() {
    console.log('PurchaseList 组件已加载');
    this.fetchVarietyTypes(); 
    this.getProductList();
  },
  // ... existing code ...
  data() {
    return {
      queryInfo: {
        query: '',
        pageNum: 1,
        pageSize: 20,
        sortBy: '',     // 排序字段
        order: ''   // 排序顺序 asc/desc
      },
      selectedVarietyType: "", // 初始化为空
      varietyTypes: [],        
      productList: [],
      total: 0
    };
  },
  mounted() {
    this.getProductList();
  },

  methods: {
  async handleSortChange({ column, prop, order }) {
    if (order === 'ascending') {
      this.queryInfo.sortBy = prop;
      this.queryInfo.order = 'asc';
    } else if (order === 'descending') {
      this.queryInfo.sortBy = prop;
      this.queryInfo.order = 'desc';
    } else {
      this.queryInfo.sortBy = '';
      this.queryInfo.order = '';
    }

    await this.getProductList(); // 重新加载数据
  },
  async handleSizeChange(newSize) {
    this.queryInfo.pageSize = newSize;
    await this.getProductList();
  },
  async handleCurrentChange(newPage) {
    this.queryInfo.pageNum = newPage;
    await this.getProductList();
  },
async getProductList() {
  const params = {
    pageNum: this.queryInfo.pageNum,
    pageSize: this.queryInfo.pageSize,
    product: this.queryInfo.query,
    sortBy: this.queryInfo.sortBy,
    order: this.queryInfo.order
  };

  if (this.selectedVarietyType) {
    params.varietyType = this.selectedVarietyType;
  }

  console.log('发送请求参数:', params); // 检查参数是否正确

  try {
    const response = await axios.get('/agricultural/prices/paged', { params });
    this.productList = response.data.data || [];
    this.total = response.data.total || 0;
    console.log('接口返回结果:', this.productList);
  } catch (error) {
    console.error('获取商品列表失败:', error);
    this.$message.error('获取商品列表失败，请稍后再试');
  }

    },
  async refreshData() {
    try {
      // 调用后端API删除quantity为0的数据
      const response = await axios.delete('/agricultural/prices/delete-zero-quantity');
      
      if (response.status === 200) {
        // 删除成功后重新获取商品列表
        await this.getProductList();
        console.log('数据刷新成功');
      } else {
        console.error('删除quantity为0的数据失败');
      }
    } catch (error) {
      console.error('发生错误:', error);
    }
    },

  async handlePurchase(row) {
  // 显示商品信息的 HTML 内容
  const productInfoHTML = `
    <div style="text-align: left; margin-bottom: 15px;">
      <p><strong>商品名称：</strong>${row.product}</p>
      <p><strong>批发价：</strong>${row.bulkPrice.toFixed(2)} 元/吨</p>
      <p><strong>产地：</strong>${row.origin}</p>
      <p><strong>当前库存：</strong>${row.quantity} 吨</p>
    </div>
  `;

  // 获取仓库地址列表
  let warehouseLocations = [];
  try {
    const locationResponse = await axios.get('/warehouse/locations');
    warehouseLocations = locationResponse.data.data || [];
    if (warehouseLocations.length === 0) {
      this.$message.warning('暂无可用仓库地址');
      return;
    }
  } catch (error) {
    console.error('获取仓库地址失败:', error);
    this.$message.error('无法加载仓库地址，请稍后再试');
    return;
  }

  // 构建下拉选项的 HTML
  const locationOptions = warehouseLocations
    .map(location => `<option value="${location}">${location}</option>`)
    .join('');

  const customContent = `
    ${productInfoHTML}
    <div style="margin-bottom: 15px;">
      <label for="locationSelect" style="display: block; margin-bottom: 5px;"><strong>选择仓库地址：</strong></label>
      <select id="locationSelect" style="width: 100%; padding: 5px;">
        ${locationOptions}
      </select>
    </div>
    <div style="margin-bottom: 15px;">
      <label for="quantityInput"><strong>请输入采购数量（吨）：</strong></label>
      <input id="quantityInput" type="number" min="1" style="width: 100%; padding: 5px;" />
    </div>
  `;

  const confirmed = await this.$alert(customContent, '采购商品', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    dangerouslyUseHTMLString: true,
    type: 'info',
    callback: async (action) => {
      if (action === 'confirm') {
        const selectedLocation = document.getElementById('locationSelect').value;
        const quantity = parseInt(document.getElementById('quantityInput').value);

        if (!selectedLocation || !quantity) {
          this.$message.error('请选择仓库地址并输入采购数量');
          return;
        }

        if (quantity <= 0) {
          this.$message.error('请输入大于0的整数');
          return;
        }

        // 获取员工ID（username）
        const employeeUsername = localStorage.getItem('employeeId');

        if (!employeeUsername) {
          this.$message.error('未找到员工信息，请重新登录');
          return;
        }

        // 构造入库请求体
        const inData = {
          employeeUsername: employeeUsername,
          product_name: row.product,
          quantity: quantity,
          price: row.bulkPrice,
          origin: row.origin,
          location: selectedLocation   // 新增字段
        };

        try {
          // 发送入库请求
          const response = await axios.post('/inventory/in', inData);

          if (response.data.code === 200) {
            this.$message.success('入库成功，库存已更新');
            await this.getProductList(); // 刷新列表
          } else {
            this.$message.error(response.data.message || '入库失败');
          }
        } catch (error) {
          console.error('入库失败:', error);
          this.$message.error('网络错误，请稍后再试');
        }
      }
    }
  }).catch(() => {
    this.$message.info('已取消');
  });
    },
    async fetchVarietyTypes() {
      try {
        const response = await axios.get('/agricultural/variety-types');
        console.log('接口返回种类:', response.data);

        // 转换数据结构为字符串数组
        this.varietyTypes = response.data.map(item => item.varietyType);

        // 设置默认为空，表示“无”
        this.selectedVarietyType = '';
      } catch (error) {
        console.error('获取种类失败:', error);
        this.$message.error('无法加载种类，请检查网络或稍后再试');
      }
    }
    
  }

};
</script>